<?php

define("TOKEN", "weixin");

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{   
    
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
            
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            if ($RX_TYPE == "text") {
                $result = $this->receiveText($postObj);
            }
            
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注，你可以输入任何文本消息然后上墙";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        
        $result = $this->transmitText($object, $content);
        
        return $result;
    }

    private function receiveText($object)
    {	

        $c = new SaeCounter();
    	$mysql = new SaeMysql();
    	 
        $text = trim($object->Content);
        if(strstr($text, "排队")){
            // $c = new SaeCounter();
            $jiao = $c->get('Queuing'); 

            // $mysql = new SaeMysql();

            $sql = "SELECT * FROM Queuing WHERE q_openid = '{$object->FromUserName}'";
            $data = $mysql->getData($sql);
            $user = $data[0][q_openid];

            if (empty($user)) {
                $sql1 = "INSERT INTO Queuing VALUES (NULL, '{$object->FromUserName}')";
                $mysql->runSql($sql1);
                $sql = "select * from Queuing where q_openid = '{$object->FromUserName}'";
                $data = $mysql->getData($sql);
            }

            $id = $data[0][q_id];
            $id = intval($id);

            $num = $id-$jiao;
            $content = "你的排号是 " . $id . "\r\n当前是 " . $jiao . " 号，\r\n前面还有 " . $num . " 人";
            $result = $this->transmitText($object, $content);
        }else{
            include("token.php");				
            $openid = $object->FromUserName;

            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $a = curl_exec($ch);

            $info = json_decode($a);

            $name = $info->nickname;					
            $headimg = $info->headimgurl;

            // $mysql = new SaeMysql();
            $sql = "INSERT INTO wx_wall VALUES (NULL, '{$name}', '{$openid}', '{$headimg}', '{$text}', NOW())";

            if($mysql->runSql($sql)){
        	   $result = $this->transmitText($object, "你发送的 “{$text}” 上墙成功 ：）");
        	   $sql = "SELECT * FROM wx_wall";
        	   $len = count($mysql->getData($sql));
        	   $nel = $len - 1;

        	   // $c = new SaeCounter();
        	   $c->set('len', $len);
        	   $c->set('nel', $nel);
            }else{
        	   $result = $this->transmitText($object, "上墙失败，请重试 ：（，ps：目前暂时只支持30个中文字符");
            }
        }

        return $result;
    }

    private function transmitText($object, $content)
    {
        $xmlTpl = "<xml>
                   <ToUserName><![CDATA[%s]]></ToUserName>
                   <FromUserName><![CDATA[%s]]></FromUserName>
                   <CreateTime>%s</CreateTime>
                   <MsgType><![CDATA[text]]></MsgType>
                   <Content><![CDATA[%s]]></Content>
                   </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        
        return $result;
    }

    
}
?>